package cn.itcast.service.impl;

import cn.itcast.entity.RedisConstant;
import cn.itcast.mapper.OrderSettingMapper;
import cn.itcast.pojo.OrderSetting;
import cn.itcast.service.OrderSettingService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingMapper mapper;

    @Autowired
    JedisPool jedisPool;



    public void editNumberByDate(OrderSetting os) {
        //由于业务逻辑相同直接调用excel批量导入的add方法进行添加或修改
        List<OrderSetting> list = new ArrayList<>();
        list.add(os);

        this.add(list);
    }

    @Override
    public List<Map<String, Object>> findAll() {
        return mapper.findAll();
    }


    @Transactional
    public void add(List<OrderSetting> list) {


        if(list != null && list.size() > 0) {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            //判断redis中是否存在相同日期
            Set<String> set = jedisPool.getResource().smembers(RedisConstant.ORDER_DATE);

            for(OrderSetting os : list) {

                //如果不存在则进行保存操作反之进行修改操作
                if(!set.contains(sdf.format(os.getOrderDate()))) {
                    mapper.add(os);
                    //将数据保存到redis数据中
                    jedisPool.getResource().sadd(RedisConstant.ORDER_DATE, sdf.format(os.getOrderDate()));

                } else {

                    mapper.editNumberByOrderDate(os);

                }
            }
        }
    }



    @Override
    public List<Map> getOrderSettingByMonth(String date) {


        //日期拼接
        String begin = date + "-1";
        String end = date + "-31";


        return mapper.getOrderSettingByMonth(begin, end);
    }


}
